"use strict"

var ejs = require('ejs')
var heredoc = require('heredoc')
var crypto = require('crypto')

var tpl = heredoc(function(){/*
	<!DOCTYPE html>
	<html>
		<head>
			<title>搜电影</title>
			<meta name='viewport' content="initial-scale=1,maximum-scale=1,minimum-scale=1">
			<script src="http://zeptojs.com/zepto-docs.min.js"></script>
			<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
		</head>
		<body>
			<h1>点击标题，开始录音翻译</h1>
			<p id="title"></p>
			<div id="director"></div>
			<div id="year"></div>
			<div id="poster"></div>
			<script>
				wx.config({
				    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				    appId: 'wx1028b6d8dae61060', // 必填，公众号的唯一标识
				    timestamp:'<%= timestamp%>' , // 必填，生成签名的时间戳
				    nonceStr: '<%= noncestr%>', // 必填，生成签名的随机串
				    signature: '<%= signature%>',// 必填，签名，见附录1
				    jsApiList: [
				    	'onMenuShareTimeline',
						'onMenuShareAppMessage',
						'onMenuShareQQ',
						'onMenuShareWeibo',
						'onMenuShareQZone',
						'startRecord',
						'stopRecord',
						'onVoiceRecordEnd',
						'translateVoice',
						'previewImage'
				    ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				});

				wx.ready(function(){
					wx.checkJsApi({
						jsApiList: ['onVoiceRecordEnd'],
						success: function(res){
							console.log(res)
						}
					})
				})

				var shareContent = {
					title:'搜搜搜',
					desc:'我搜出来了啥 ',
					link:'https://baidu.com',
					imgUrl: 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png',
					success:function(){
						window.alert('分享成功')
					},
					cancel:function(){
						window.alert('分享失败')
					}
				}
				var slides
				var isRecording = false
				
				$('#poster').on('tap',function(){
					wx.previewImage(slides)
				})

				$('h1').on('tap',function(){
					if(!isRecording){
						isRecording = true
						wx.startRecord({
							cancel: function(){
								window.alert('那就不能搜了哈')
							}
						});
						return
					}
					isRecording = false

					wx.stopRecord({
						success: function (res){
							var localId = res.localId

							wx.translateVoice({
								localId: localId,
								isShowProgressTips: 1,
								success: function (res){
									var result = res.translateResult

									$.ajax({
										type: 'get',
										url:'https://api.douban.com/v2/movie/search?q=' + result,
										dataType: 'jsonp',
										jsonp: 'callback',
										success: function(data){
											var subject = data.subjects[0]

											$('#title').html(subject.title)
											$('#year').html(subject.year)
											$('#director').html(subject.directors[0].name)
											$('#poster').html('<img src="' + subject.images.large + '" />')

											shareContent = {
												title:subject.title,
												desc:'我搜出来了 ' + subject.title,
												link:'https://baidu.com',
												imgUrl: subject.images.large,
												success:function(){
													window.alert('分享成功')
												},
												cancel:function(){
													window.alert('分享失败')
												}
											}
											slides = {
												current: subject.images.large ,
												urls: [subject.images.large]
											}

											data.subjects.forEach(function(item){
												slides.urls.push(item.images.large)
											})
											
											wx.onMenuShareAppMessage(shareContent)
										}
									})
								}
							})
						}
					})
				})
			</script>
		</body>
	</html>
*/})

var creatNonce = function(){
	return Math.random().toString(36).substr(2,15)
}

var createTimestamp = function(){
	return parseInt(new Date().getTime() / 1000,10) + ''
}

var _sign = function(noncestr,ticket,timestamp,url){
	var params = [
		'noncestr=' + noncestr,
		'jsapi_ticket=' + ticket,
		'timestamp=' + timestamp,
		'url=' + url
	]

	var str = params.sort().join('&')
	var shasum = crypto.createHash('sha1')

	shasum.update(str)
	return shasum.digest('hex')
}

function sign(ticket,url) {
	var noncestr = creatNonce()
	var timestamp = createTimestamp()
	var signature = _sign(noncestr,ticket,timestamp,url)

	console.log(ticket)
	console.log(url)
	return {
		noncestr: noncestr,
		timestamp: timestamp,
		signature: signature
	}
}

var wx = require('../../wx/index')

exports.movie = function *(next){

	var wechatApi = wx.getWechat()
	var data = yield wechatApi.fetchAccessToken()
	var access_token = data.access_token
	var ticketData = yield wechatApi.fetchTicket(access_token)
	var ticket = ticketData.ticket
	var url = this.href
	var params = sign(ticket,url)

	this.body = ejs.render(tpl,params)

}

